﻿using System.Text;

namespace SenGe.Domain.Utils
{
    /// <summary>
    /// 日志帮助类
    /// </summary>
    public static class LogUtil
    {
        /// <summary>
        /// 初始化系统锁
        /// </summary>
        private static readonly SemaphoreSlim Sem = new SemaphoreSlim(1);
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="msg">日志信息</param>
        /// <param name="fileName">日志文件全路径(可为空，为空时默认写入运行目录下的test.log文件)</param>
        public static async void WriteLog(string msg, string fileName = "")
        {
            await Sem.WaitAsync();
            try
            {
                if (string.IsNullOrEmpty(msg)) return;
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.log");
                }
                using (StreamWriter sw = new StreamWriter(fileName, true, Encoding.UTF8))
                {
                    string timeFlag = $"------------------------{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}------------------------";
                    sw.WriteLine(timeFlag);
                    await Console.Out.WriteLineAsync(timeFlag);
                    await sw.WriteLineAsync(msg);
                    await Console.Out.WriteLineAsync(msg);
                }
            }
            catch { }
            finally
            {
                Sem.Release();
            }
        }
    }
}
